// Mock API拦截器 - 用于拦截和模拟实盘页面的所有API请求

import {
  generateCryptoPrices,
  generateAccountTotals,
  generatePositions,
  generateTrades,
  generateSinceInceptionValues,
  generateConversations,
  generateLeaderboard,
  generateAnalytics,
  generateModelAnalytics
} from './mockDataGenerator';

// 原始fetch方法
const originalFetch = window.fetch;

// 是否启用Mock
let isMockEnabled = true;

/**
 * 启用或禁用Mock
 */
export function setMockEnabled(enabled: boolean) {
  isMockEnabled = enabled;
  console.log(`Mock API ${enabled ? 'enabled' : 'disabled'}`);
}

/**
 * 模拟网络延迟
 */
function mockDelay(ms: number = 300): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * 解析URL参数
 */
function getQueryParams(url: string): Record<string, string> {
  const params: Record<string, string> = {};
  const searchParams = new URL(url).searchParams;
  searchParams.forEach((value, key) => {
    params[key] = value;
  });
  return params;
}

/**
 * 检查是否为需要拦截的API路径
 */
function isNof1ApiRequest(url: string): boolean {
  return url.includes('/api/nof1/');
}

/**
 * 处理Mock API请求
 */
async function handleMockRequest(url: string, options: RequestInit): Promise<Response> {
  // 模拟网络延迟
  await mockDelay(Math.random() * 200 + 100);
  
  // 移除代理前缀，只保留实际路径
  const path = url.replace(/.*\/api\/nof1/, '');
  console.log(`Mock API request: ${path}`);
  
  let responseData: any;
  let status = 200;
  
  // 解析查询参数
  const params = getQueryParams(url);
  
  try {
    console.log('正在请求模拟数据：',path);
    // 根据路径分发到不同的模拟数据生成函数
    if (path === '/crypto-prices') {
      responseData = generateCryptoPrices();
    } else if (path === '/account-totals' || path.startsWith('/account-totals?')) {
      const lastHourlyMarker = params.lastHourlyMarker ? parseInt(params.lastHourlyMarker, 10) : undefined;
      responseData = generateAccountTotals(lastHourlyMarker);
    } else if (path === '/positions' || path.startsWith('/positions?')) {
      const limit = params.limit ? parseInt(params.limit, 10) : 1000;
      responseData = generatePositions(limit);
    } else if (path === '/trades') {
      responseData = generateTrades();
    } else if (path === '/since-inception-values') {
      responseData = generateSinceInceptionValues();
    } else if (path === '/conversations') {
      responseData = generateConversations();
    } else if (path === '/leaderboard') {
      responseData = generateLeaderboard();
    } else if (path === '/analytics') {
      responseData = generateAnalytics();
    } else if (path.startsWith('/analytics/')) {
      // 处理模型特定分析接口
      const modelId = path.split('/')[2];
      responseData = generateModelAnalytics(modelId);
    } else {
      // 未知路径，返回404
      status = 404;
      responseData = { error: 'Not found', message: `No mock data for path: ${path}` };
    }
  } catch (error) {
    // 生成数据时出错
    status = 500;
    responseData = { error: 'Internal Server Error', message: (error as Error).message };
    console.error('Error generating mock data:', error);
  }
  
  // 记录响应
  console.log(`Mock API response ${status}:`, JSON.stringify(responseData).substring(0, 200) + '...');
  
  // 返回模拟的Response对象
  return new Response(JSON.stringify(responseData), {
    status,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'X-Mock-Response': 'true'
    }
  });
}

/**
 * 初始化Mock API
 */
export function initMockApi(): void {
  // 只在浏览器环境中运行
  if (typeof window === 'undefined') {
    return;
  }
  
  // 保存原始fetch方法的引用（如果尚未保存）
  
  // 重写fetch方法
  (window as any).fetch = async (url: string, options?: RequestInit): Promise<Response> => {
    // 检查是否启用了Mock以及是否为需要拦截的API
    if (isMockEnabled && isNof1ApiRequest(url)) {
      return handleMockRequest(url, options || {});
    }
    
    // 对于非Mock请求，使用原始fetch
    return originalFetch(url, options);
  };
  
  console.log('Mock API initialized - intercepting /api/nof1/* requests');
}

/**
 * 创建一个模拟数据导出工具
 */
export function exportMockData() {
  return {
    cryptoPrices: generateCryptoPrices(),
    accountTotals: generateAccountTotals(),
    positions: generatePositions(),
    trades: generateTrades(),
    sinceInceptionValues: generateSinceInceptionValues(),
    conversations: generateConversations(),
    leaderboard: generateLeaderboard(),
    analytics: generateAnalytics(),
    modelAnalytics: generateModelAnalytics('qwen3-max')
  };
}

// 默认导出
const mockApi = {
  init: initMockApi,
  setEnabled: setMockEnabled,
  exportData: exportMockData
};

export default mockApi;